<template>
  <div class="shopping-cart">
    <MyPanel title="购物车" subTitle="您选购的商品">
      <div v-if="cartItems.length > 0" class="cart-content">
        <!-- 购物车商品列表 -->
        <div class="cart-items">
          <div 
            class="cart-item" 
            v-for="item in cartItems" 
            :key="item.cartId"
          >
            <div class="item-checkbox">
              <input 
                type="checkbox" 
                :checked="item.selected" 
                @change="toggleItemSelection(item)"
              />
            </div>
            
            <div class="item-image">
              <img :src="item.product.imageUrl" :alt="item.product.productName" />
            </div>
            
            <div class="item-info">
              <div class="item-name">{{ item.product.productName }}</div>
              <div class="item-price">¥{{ item.product.price }}</div>
            </div>
            
            <div class="item-quantity">
              <button 
                class="quantity-btn" 
                @click="decreaseQuantity(item)"
                :disabled="item.quantity <= 1"
              >
                -
              </button>
              <span class="quantity">{{ item.quantity }}</span>
              <button 
                class="quantity-btn" 
                @click="increaseQuantity(item)"
              >
                +
              </button>
            </div>
            
            <div class="item-total">
              ¥{{ (item.product.price * item.quantity).toFixed(2) }}
            </div>
            
            <div class="item-actions">
              <button class="delete-btn" @click="removeItem(item.cartId)">
                删除
              </button>
            </div>
          </div>
        </div>
        
        <!-- 购物车底部操作栏 -->
        <div class="cart-footer">
          <div class="footer-left">
            <input 
              type="checkbox" 
              :checked="allSelected" 
              @change="toggleAllSelection"
            />
            <span>全选</span>
            <button class="clear-btn" @click="clearCart">清空购物车</button>
          </div>
          
          <div class="footer-right">
            <div class="total-info">
              <span>已选 {{ selectedCount }} 件商品</span>
              <span class="total-price">总价: ¥{{ totalPrice.toFixed(2) }}</span>
            </div>
            <button class="checkout-btn" @click="checkout">去结算</button>
          </div>
        </div>
      </div>
      
      <!-- 空购物车提示 -->
      <div v-else class="empty-cart">
        <div class="empty-icon">
          <i class="iconfont icon-cart"></i>
        </div>
        <p>购物车还是空的，赶紧去选购商品吧！</p>
        <router-link to="/" class="go-shopping-btn">
          去逛逛
        </router-link>
      </div>
    </MyPanel>
  </div>
</template>

<script>
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import MyPanel from "@/components/MyPanel.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getCartItems, updateCartItem, deleteCartItem } from "@/api";

export default {
  components: {
    MyPanel
  },
  setup() {
    const cartItems = ref([]);
    
    // 获取购物车数据
    const fetchCartItems = async () => {
      try {
        const res = await getCartItems();
        if (res.code === 200) {
          // 为每个购物车项添加selected属性
          cartItems.value = res.data.map(item => ({
            ...item,
            selected: true
          }));
        } else {
          ElMessage.error(res.message || "获取购物车数据失败");
        }
      } catch (error) {
        console.error("获取购物车数据失败:", error);
        ElMessage.error("获取购物车数据失败");
      }
    };
    
    // 增加商品数量
    const increaseQuantity = (item) => {
      item.quantity++;
      updateCartItemQuantity(item.cartId, item.quantity);
    };
    
    // 减少商品数量
    const decreaseQuantity = (item) => {
      if (item.quantity > 1) {
        item.quantity--;
        updateCartItemQuantity(item.cartId, item.quantity);
      }
    };
    
    // 更新购物车商品数量
    const updateCartItemQuantity = async (cartId, quantity) => {
      try {
        const res = await updateCartItem(cartId, { quantity });
        if (res.code !== 200) {
          ElMessage.error(res.message || "更新商品数量失败");
        }
      } catch (error) {
        console.error("更新商品数量失败:", error);
        ElMessage.error("更新商品数量失败");
      }
    };
    
    // 切换商品选择状态
    const toggleItemSelection = (item) => {
      item.selected = !item.selected;
    };
    
    // 全选/取消全选
    const toggleAllSelection = () => {
      const newSelectedState = !allSelected.value;
      cartItems.value.forEach(item => {
        item.selected = newSelectedState;
      });
    };
    
    // 删除购物车项
    const removeItem = async (cartId) => {
      try {
        await ElMessageBox.confirm("确定要删除该商品吗？", "提示", {
          type: "warning"
        });
        
        const res = await deleteCartItem(cartId);
        if (res.code === 200) {
          // 从本地列表中移除
          cartItems.value = cartItems.value.filter(item => item.cartId !== cartId);
          ElMessage.success("删除成功");
        } else {
          ElMessage.error(res.message || "删除商品失败");
        }
      } catch (error) {
        if (error !== "cancel") {
          console.error("删除商品失败:", error);
          ElMessage.error("删除商品失败");
        }
      }
    };
    
    // 清空购物车
    const clearCart = async () => {
      try {
        await ElMessageBox.confirm("确定要清空购物车吗？", "提示", {
          type: "warning"
        });
        
        // 逐个删除购物车项
        const deletePromises = cartItems.value.map(item => 
          deleteCartItem(item.cartId)
        );
        
        const results = await Promise.all(deletePromises);
        const failedCount = results.filter(res => res.code !== 200).length;
        
        if (failedCount === 0) {
          // 清空本地列表
          cartItems.value = [];
          ElMessage.success("购物车已清空");
        } else {
          ElMessage.warning(`有 ${failedCount} 个商品删除失败`);
          // 重新获取购物车数据以同步状态
          fetchCartItems();
        }
      } catch (error) {
        if (error !== "cancel") {
          console.error("清空购物车失败:", error);
          ElMessage.error("清空购物车失败");
        }
      }
    };
    
    // 去结算
    const checkout = () => {
      const selectedItems = cartItems.value.filter(item => item.selected);
      if (selectedItems.length === 0) {
        ElMessage.warning("请至少选择一件商品");
        return;
      }
      
      // 使用router跳转到结算页面
      router.push('/checkout');
    };
    
    // 计算属性
    const allSelected = computed(() => {
      return cartItems.value.length > 0 && 
        cartItems.value.every(item => item.selected);
    });
    
    const selectedCount = computed(() => {
      return cartItems.value
        .filter(item => item.selected)
        .reduce((count, item) => count + item.quantity, 0);
    });
    
    const totalPrice = computed(() => {
      return cartItems.value
        .filter(item => item.selected)
        .reduce((total, item) => total + (item.product.price * item.quantity), 0);
    });
    
    // 获取router实例
    const router = useRouter();
    
    onMounted(() => {
      fetchCartItems();
    });
    
    return {
      cartItems,
      allSelected,
      selectedCount,
      totalPrice,
      increaseQuantity,
      decreaseQuantity,
      toggleItemSelection,
      toggleAllSelection,
      removeItem,
      clearCart,
      checkout
    };
  }
};
</script>

<style lang="less" scoped>
@import "@/assets/styles/variables.less";

.shopping-cart {
  .cart-content {
    .cart-items {
      .cart-item {
        display: flex;
        align-items: center;
        padding: 20px 0;
        border-bottom: 1px solid #eee;
        
        .item-checkbox {
          width: 40px;
          text-align: center;
        }
        
        .item-image {
          width: 100px;
          height: 100px;
          margin: 0 20px;
          
          img {
            width: 100%;
            height: 100%;
            object-fit: contain;
          }
        }
        
        .item-info {
          flex: 1;
          
          .item-name {
            font-size: 16px;
            margin-bottom: 10px;
          }
          
          .item-price {
            font-size: 18px;
            color: @priceColor;
            font-weight: bold;
          }
        }
        
        .item-quantity {
          display: flex;
          align-items: center;
          margin: 0 20px;
          
          .quantity-btn {
            width: 30px;
            height: 30px;
            background-color: #f5f5f5;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            
            &:disabled {
              cursor: not-allowed;
              opacity: 0.5;
            }
            
            &:hover:not(:disabled) {
              background-color: #e0e0e0;
            }
          }
          
          .quantity {
            margin: 0 10px;
            font-size: 16px;
            min-width: 30px;
            text-align: center;
          }
        }
        
        .item-total {
          width: 120px;
          text-align: center;
          font-size: 18px;
          color: @priceColor;
          font-weight: bold;
        }
        
        .item-actions {
          width: 80px;
          text-align: center;
          
          .delete-btn {
            color: #999;
            background: none;
            border: none;
            cursor: pointer;
            
            &:hover {
              color: @xtxColor;
            }
          }
        }
      }
    }
    
    .cart-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px 0;
      border-top: 1px solid #eee;
      
      .footer-left {
        display: flex;
        align-items: center;
        
        input {
          margin-right: 10px;
        }
        
        span {
          margin-right: 20px;
        }
        
        .clear-btn {
          background: none;
          border: none;
          color: #999;
          cursor: pointer;
          
          &:hover {
            color: @xtxColor;
          }
        }
      }
      
      .footer-right {
        display: flex;
        align-items: center;
        
        .total-info {
          margin-right: 20px;
          
          .total-price {
            margin-left: 20px;
            font-size: 20px;
            color: @priceColor;
            font-weight: bold;
          }
        }
        
        .checkout-btn {
          width: 120px;
          height: 40px;
          background-color: @xtxColor;
          color: white;
          border: none;
          border-radius: 4px;
          font-size: 16px;
          cursor: pointer;
          
          &:hover {
            background-color: #b8884d;
          }
        }
      }
    }
  }
  
  .empty-cart {
    text-align: center;
    padding: 50px 0;
    
    .empty-icon {
      font-size: 80px;
      color: #ccc;
      margin-bottom: 20px;
    }
    
    p {
      font-size: 18px;
      color: #666;
      margin-bottom: 30px;
    }
    
    .go-shopping-btn {
      display: inline-block;
      padding: 10px 30px;
      background-color: @xtxColor;
      color: white;
      border-radius: 4px;
      text-decoration: none;
      
      &:hover {
        background-color: #b8884d;
      }
    }
  }
}
</style>